package com.zhengb.algorithmdemo.sort;

import java.util.*;

/**
 * 两个集合交集
 *
 * @author zhengbo
 * @date 2020/2/17
 */
public class CollectionIntersection {

    public static Set<Integer> getListIntersection(List<Integer> listA, List<Integer> listB) {

        int listASize = listA.size();

        int listBSize = listB.size();

        List<Integer> mailList;

        List<Integer> compareList;
        //选择size较小的进行迭代
        if (listASize <= listBSize) {
            mailList = listA;
            compareList = listB;
        } else {
            mailList = listB;
            compareList = listA;
        }

        Set<Integer> result = new HashSet<>();

        Iterator<Integer> iterator = mailList.iterator();

        while (iterator.hasNext()) {
            Integer next = iterator.next();

            if (compareList.contains(next)) {
                result.add(next);
            }
        }

        return result;
    }

    public static void main(String[] args) {

        int[] arrayA = new int[]{1, 3, 5, 6};
        int[] arrayB = new int[]{3, 4, 5};

        List<Integer> listA = new LinkedList<>();
        for (int i : arrayA) {
            listA.add(i);
        }

        List<Integer> listB = new LinkedList<>();
        for (int i : arrayB) {
            listB.add(i);
        }

        Set<Integer> listIntersection = getListIntersection(listA, listB);

        System.out.println(Arrays.asList(listIntersection.toArray()));
    }
}
